'''
Created on 2010-8-2

@author: wangjo
'''
import sys
sys.path.insert(0 , "gdata.zip")

import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
import gdata.maps.client
import gdata.gauth
import settings
import models
import utility

def get_map_client():
    client = gdata.maps.client.MapsClient()
    key = "token"
    token_string = models.setting.get(key)
    if token_string is None:
        logging.info("request login token from Google Server")
        client.ClientLogin(email=settings.GA_USER, password=settings.GA_PWD, source=settings.APP_NAME, account_type="GOOGLE")
        token = client.auth_token
        token_string = token.token_string
        logging.info("token:%s"%token_string)
        models.setting.set(key, token_string)
    else:
        client.auth_token = gdata.gauth.ClientLoginToken(token_string)
    return client

class HomeHandler(utility.TemplateSupportRequestHandler):
    def get(self):
        client = get_map_client()
        feed = client.GetMaps()
        self.generate("index.html", {"entries": feed.entry})
        
    def post(self):
        client = get_map_client()
        msg = None
        name = self.request.get("name")
        logging.info("new map name:%s"%name)
        if len(name.strip()) > 0:
            map = client.CreateMap(name, summary="Google Maps API demo", unlisted=True)
            if map is None:
                msg = "create map failed"
        else:
            msg = "map name could not be null or empty"
        feed = client.GetMaps()
        self.generate("index.html", {"entries": feed.entry, "warn": msg})

class MapHandler(utility.TemplateSupportRequestHandler):
    def get(self, mid):
        client = get_map_client()
        logging.info("map id:%s"%mid)
        feed = client.GetFeatures(mid)
        self.generate("map.html", {"mapid": mid,
                                   "feed": feed,
                                   "features": feed.entry})
    
    def post(self, mid):
        client = get_map_client()
        msg = None
        name = self.request.get("name")
        logging.info("new feature name:%s"%name)
        if len(name.strip()) > 0:
            lat=33.5043 
            lng=-111.956
            kml = getKmlContent(lat, lng, name, chain="KFC", ischain=True, location="China,Shanghai")
            logging.info("kml content:%s"%kml)
            feature = client.AddFeature(mid, name, kml.encode('ascii','ignore'))
            if feature is None:
                msg = "create feature failed"
        else:
            msg = "feature name could not be null or empty"
        feed = client.GetFeatures(mid)
        self.generate("map.html", {"mapid": mid,
                                   "feed": feed,
                                   "features": feed.entry})
    
def getKmlContent(lat, lng, name, desc=None, **kwargs):
    kml = "<Placemark><name>%s</name>%s</Placemark>"
    point = "<Point><coordinates>%f,%f,0.0</coordinates></Point>"%(float(lng), float(lat))
    content = ""
    if desc is not None:
        content += '<description>%s</description>'%desc
    if len(kwargs) > 0:
        items = ""
        for key in kwargs:
            items += '<Data name="%s"><value>%s</value></Data>'%(key, kwargs[key])
        content += "<ExtendedData>%s</ExtendedData>"%items
    content += point
    return kml%(name, content)

class SearchHandler(utility.TemplateSupportRequestHandler):
    def get(self):
        client = get_map_client()
        uid = "209620911337266780143"
        mid = "00048ce7f2dbe9f06e187"
        url = get_search_url(uid, mid, holePar="4")
        logging.info("search request url:%s"%url)
        feed = client.GetFeed(url, desired_class=gdata.maps.data.FeatureFeed)
        self.generate("search.html", {"feed": feed,
                                   "features": feed.entry})
    
def get_search_url(uid, mid, lat=33.5043, lng=-111.956, **kwargs):
    SEARCH_TEMPLATE = "http://maps.google.com/maps/feeds/features/%s/%s/snippet?lat=%f&lng=%f&radius=1000&mq=%s"
    para = ""
    for key in kwargs:
        para += "[%s:%s]"%(key, kwargs[key])
    return SEARCH_TEMPLATE%(uid, mid, lat, lng, para)
        
def main():
    application = webapp.WSGIApplication([(r'/map/(.*)', MapHandler),
                                          ('/search.*', SearchHandler),
                                          ('/.*', HomeHandler),], 
                                          debug = True)
    run_wsgi_app(application)
        
if __name__ == "__main__":
    main()    